package com.zhihuichongcheng.application.ui.im.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Pair;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.easeui.domain.EaseUser;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.smartlib.cmnObject.recycleView.OnItemOnclick;
import com.zhihuichongcheng.application.R;
import com.zhihuichongcheng.application.base.BaseActivity;
import com.zhihuichongcheng.application.bean.mine.UserBean;
import com.zhihuichongcheng.application.im.Constant;
import com.zhihuichongcheng.application.ui.im.adapter.EaseConversationAdapter;
import com.zhihuichongcheng.application.util.EaseUserUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * Created by 3water on 2016/10/27.
 */

public class ImSearchActivity extends BaseActivity implements View.OnClickListener{
    private EditText mEtSearch;
    private ImageView mImDel;
    private TextView mTvCancel;
    private List<EMConversation> mListData = new ArrayList<>();
    private List<EMConversation> mListSearch = new ArrayList<>();
    private XRecyclerView mEaseConversationList;
    private EaseConversationAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_im_search);
        initView();
        initData();
    }

    private void initView()
    {
        setStatusBarDarkMode();
        mTvCancel = (TextView)findViewById(R.id.tv_cancel);
        mTvCancel.setOnClickListener(this);
        mEtSearch = (EditText)findViewById(R.id.et_search);
        mEtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(s.length()>0)
                {
//                    mEaseConversationList.filter(s);
                    mAdapter.setData(filter(s.toString().trim()));
                    if (mAdapter.getItemCount() > 0)
                    {
                        mEaseConversationList.setVisibility(View.VISIBLE);
                        mAdapter.notifyDataSetChanged();
//                        mEaseConversationList.init(mListSearch);
                    }

                    mImDel.setVisibility(View.VISIBLE);
                }
                else
                {
                    mEaseConversationList.setVisibility(View.GONE);
                    mImDel.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {


            }
        });
        mImDel = (ImageView)findViewById(R.id.im_del);
        mEaseConversationList = (XRecyclerView) findViewById(R.id.list);
        mEaseConversationList.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = new EaseConversationAdapter(getContext(), 0, mListSearch);
        mEaseConversationList.setAdapter(mAdapter);
        mImDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEtSearch.setText("");
            }
        });
        mAdapter.setOnItemOnclick(new OnItemOnclick<EMConversation>() {
            @Override
            public void onClick(EMConversation emConversation, int position) {
//                EMConversation conversation = mListSearch.get(position);
//                String username = conversation.getUserName();
//                if (username.equals(EMClient.getInstance().getCurrentUser())) {
//                    Toast.makeText(mContext, R.string.Cant_chat_with_yourself, Toast.LENGTH_SHORT).show();
//                } else {
//                    Bundle bundle = new Bundle();
//                    bundle.putString(Constant.EXTRA_USER_ID, username);
//                    if (conversation.isGroup()) {
//                        if (conversation.getType() == EMConversation.EMConversationType.ChatRoom) {
//                            // it's group chat
//                            bundle.putInt(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_CHATROOM);
//                        } else {
//                            bundle.putInt(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_GROUP);
//                        }
//                    }
//                    startActivity(ChatActivity.class,bundle);
//                }
                String username = emConversation.getUserName();
                if (username.equals(EMClient.getInstance().getCurrentUser()))
                    Toast.makeText(getContext(), R.string.Cant_chat_with_yourself, Toast.LENGTH_SHORT).show();
                else {
                    Intent intent = new Intent(getContext(), ChatActivity.class);
                    if (emConversation.isGroup()) {
                        if (emConversation.getType() == EMConversation.EMConversationType.ChatRoom) {
                            intent.putExtra(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_CHATROOM);
                        } else {
                            intent.putExtra(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_GROUP);
                        }

                    }
                    // it's single chat
                    intent.putExtra(Constant.EXTRA_USER_ID, username);
                    startActivity(intent);
                }
            }
        });
    }

    private void initData()
    {
        mListData = loadConversationList();
        mAdapter.notifyDataSetChanged();
//        mEaseConversationList.init(mListData);
    }

    private List<EMConversation> filter(String str) {
        List<EMConversation> newValues = new ArrayList<>();
        for (int i = 0; i < mListData.size(); i++) {
            final EMConversation value = mListData.get(i);
            String username = value.getUserName();
            EMGroup group = EMClient.getInstance().groupManager().getGroup(username);
            if (group != null) {
                username = group.getGroupName();
            } else {
                EaseUser user = EaseUserUtils.getUserInfo(username);
//                        if(user != null && user.getNick() != null)
//                            username = user.getNick();
                UserBean bean = spUtil.getObject(username, UserBean.class);
                username = bean.getUserName();
            }

            // First match against the whole ,non-splitted value
            if (username.startsWith(str)) {
                newValues.add(value);
            } else {
                final String[] words = username.split(" ");
                final int wordCount = words.length;
                // Start at index 0, in case valueText starts with space(s)
                for (String word : words) {
                    if (word.startsWith(str)) {
                        newValues.add(value);
                        break;
                    }
                }
            }
        }
        return newValues;
    }

    /**
     * load conversation list
     *
     * @return
    +    */
    protected List<EMConversation> loadConversationList(){
        // get all conversations
        Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
        List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
        /**
         * lastMsgTime will change if there is new message during sorting
         * so use synchronized to make sure timestamp of last message won't change.
         */
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
                }
            }
        }
        try {
            // Internal is TimSort algorithm, has bug
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        for (Pair<Long, EMConversation> sortItem : sortList) {
            list.add(sortItem.second);
        }
        return list;
    }

    /**
     * sort conversations according time stamp of last message
     *
     * @param conversationList
     */
    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {

                if (con1.first.equals(con2.first)) {
                    return 0;
                } else if (con2.first.longValue() > con1.first.longValue()) {
                    return 1;
                } else {
                    return -1;
                }
            }

        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.tv_cancel:
                finish();
                break;
            default:
                break;
        }
    }
}
